<?php
namespace Controllers;

use Models\CategoryModel;
use Models\PostModel;

class PostController extends CommonController {
    public function add () {
        if (!empty($_POST)) {
            // 提交操作
            if (!$this->isLogin()) return $this->responseJson(401, '尚未登录，请先登录');
            $cate_id = isset($_POST['cate_id']) ? intval($_POST['cate_id']) : 0;
            if (empty($cate_id)) return $this->responseJson(400, '请选择主题分类');
            $title = isset($_POST['title']) ? trim($_POST['title']) : '';
            if (empty($title)) return $this->responseJson(400, '请填写主题');
            $content = isset($_POST['content']) ? $_POST['content'] : '';
            if (empty($content)) return $this->responseJson(400, '请填写内容');

            $data = [
                'title' => $title,
                'content' => $content,
                'cate_id' => $cate_id,
                'user_id' => $_SESSION['user_id']
            ];
            $postModel = new PostModel();
            if ($postModel->add($data)) {
                return $this->responseJson(200, '发布成功');
            } else{
                return $this->responseJson(400, '发布失败');
            }


        } else {
            $this->noLoginJump();
            $cateModel = new CategoryModel();
            $cateLists = $cateModel->getAllCategories();
            $data = [
                'cateLists' => $cateLists
            ];
            // $cateLists
            return $this->response('post/add', $data);
        }
    }
}